package com.itheima;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Demo1 {


    @Test
    public void test() throws Exception {

        XSSFWorkbook workbook = new XSSFWorkbook();

        XSSFSheet sheet = workbook.createSheet("1");

        XSSFRow rowOne = sheet.createRow(0);

        rowOne.createCell(0).setCellValue("姓名");
        rowOne.createCell(1).setCellValue("年龄");
        rowOne.createCell(2).setCellValue("地址");

        XSSFRow rowTwo = sheet.createRow(1);
        rowTwo.createCell(0).setCellValue("1");
        rowTwo.createCell(1).setCellValue("2");
        rowTwo.createCell(2).setCellValue("3");

        FileOutputStream fos = new FileOutputStream("e:\\love.xlsx");

        workbook.write(fos);
        fos.flush();
        workbook.close();
    }

    //使用POI读取Excel文件中的数据
    //@Test
    public void test2() throws Exception{
        //加载指定文件，创建一个Excel对象（工作簿）
        XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File("e:\\poi.xlsx")));
        //读取Excel文件中第一个Sheet标签页
        XSSFSheet sheet = excel.getSheetAt(0);
        //获得当前工作表中最后一个行号，需要注意：行号从0开始
        int lastRowNum = sheet.getLastRowNum();
        System.out.println("lastRowNum = " + lastRowNum);
        for(int i=0;i<=lastRowNum;i++){
            XSSFRow row = sheet.getRow(i);//根据行号获取每一行
            //获得当前行最后一个单元格索引
            short lastCellNum = row.getLastCellNum();
            System.out.println("lastCellNum = " + lastCellNum);
            for(int j=0;j<lastCellNum;j++){
                XSSFCell cell = row.getCell(j);//根据单元格索引获得单元格对象
                System.out.println(cell.getStringCellValue());
            }
        }
        //关闭资源
        excel.close();
    }
}
